/*
 * Runs on a separate thread from Main.  Listens to opened port for 
 * competitors and sends socket back to main when new players arrive.
 */

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/*
 * Listens to port to add new players during the joining stage.  Is run
 * as a daemon and ended with an interrupt at the end of the joining stage.
 */
public class PortListener implements Runnable {

	private int maxConnections, port;
	private Boolean done = false;

	public PortListener(int portnumber, int maxConnections) {
		port = portnumber;
		this.maxConnections = maxConnections;
	}

	public void run() {

		try {
			ServerSocket listener = new ServerSocket(port);
			Socket socket;

			while (true) {
				// Don't accept new sockets if max is reached.
				while ((RubikServer.NumConnections() == maxConnections)
						&& (maxConnections != 0)) {
					Thread.yield();
				}
				// Get new socket
				socket = listener.accept();
				// If stage is over, do not attempt to add
				if (done) {
					return;
				}
				RubikServer.AddSocket(socket);
			}

		} catch (IOException ioe) {
			System.out.println("IOException on socket listen: " + ioe);
			ioe.printStackTrace();
		}

	}

	public void Stop() {
		done = true;
	}
}
